define(['jquery', 'bootstrap', 'utilback', 'table', 'form', 'treetable', 'ztree'], function ($, undefined, Utilback, Table, Form) {

    var Controller = {
    	config: {
    		get_user: '/user/read/list?permission=1',
    		get_role: '/role/read/page?permission=1',
    		get_menu: '/menu/read/list',
    		get_promission: '/menu/read/tree'
    	},
        init: function () {
            // 初始化表格参数配置
            Table.api.init({
            	singleSelect: true,
            });
            
            // 清理缓存
            $('.btn-refresh-cache').on('click', function() {
            	Util.api.ajax({
            		type: 'POST',
            		url: '/cache/update',
            		data: {key: 'Permission'}
            	});
            });
            
           this.initUserRole();
           this.initRoleMenu();
           this.initRolePromission();
        },
        initUserRole: function () {
            var userTable = $("#userTable");
            // 初始化表格
            userTable.bootstrapTable({
            	toolbar: '#toolbar1',
            	showExport: false,
                url: Controller.config.get_user,
                columns: [
                    [
                        {field: 'state', checkbox: true, },
                        {field: 'id', title: 'ID'},
                        {field: 'userName', title: __('Username')},
                        {field: 'account', title: __('Account')},
                        {field: 'deptName', title: __('Deptname')},
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(userTable);
            
            var userRoleTable = $("#userRoleTable");
            // 初始化表格
            userRoleTable.bootstrapTable({
            	toolbar: '#toolbar2',
            	showExport: false,
            	singleSelect: false,
                url: Controller.config.get_role,
                columns: [
                    [
                        {field: 'state', checkbox: true, },
                        {field: 'id', title: 'ID'},
                        {field: 'roleName', title: '角色名称'},
                        {field: 'deptName', title: __('Deptname')},
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(userRoleTable);
            
            // 根据用户查询用户角色
            userTable.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table fa.event.check', function () {
            	userRoleTable.bootstrapTable('uncheckAll');
                var ids = Table.api.selectedids(userTable);
                if(ids.length) {
                	Util.api.ajax({
                		type: 'get',
                		url: '/user/read/role',
            			data : {userId : ids[0]},
                	}, function(result) {
                		var roleIds = [];
                		if (result.code == 200) {
                			var rows = result.rows;
        					for(var i=0; i<rows.length;i++) {
        						roleIds.push(rows[i].roleId);
        					}
        				}
                		userRoleTable.bootstrapTable("checkBy", {field:"id", values: roleIds});
                	});
                }
            });
            
            // 保存用户角色
            $('#userRole').on('click', '.btn-save', function() {
            	var userIds = Table.api.selectedids(userTable);
            	var roleIds = Table.api.selectedids(userRoleTable);
            	var data = [ {userId: userIds[0], permission: 'read'} ];
            	$.each(roleIds, function(i, roleId) {
        			data.push({userId: userIds[0], roleId: roleId, permission: 'read'});
        		});
            	if(userIds.length && roleIds.length) {
                	Util.api.ajax({
                		type: 'POST',
                		url: '/user/update/role',
            			data : JSON.stringify(data),
            			contentType: 'application/json;charset=UTF-8'
                	}, function(result) {
                		Toastr.success('保存成功.');
                	});
                }
            });
        },
        initRoleMenu: function () {
            var i=0;
            var roleTable1 = $("#roleTable1");
   		 	var roleMenuTable = $("#roleMenuTable");
            $('[href="#roleMenu"]').on('click', function() {
            	if(i === 0) {
                    // 初始化表格
                    roleTable1.bootstrapTable({
                    	toolbar: '#toolbar3',
                    	showExport: false,
                    	singleSelect: true,
                        url: Controller.config.get_role,
                        columns: [
                            [
                                {field: 'state', checkbox: true, },
                                {field: 'id', title: 'ID'},
                                {field: 'roleName', title: '角色名称'},
                                {field: 'deptName', title: __('Deptname')},
                            ]
                        ]
                    });
                    // 为表格绑定事件
                    Table.api.bindevent(roleTable1);
                    
                     // 初始化表格
            		 roleMenuTable.bootstrapTable({
                     	toolbar: '#toolbar4',
                     	singleSelect: false,
                     	showExport: false,
                    	pagination: false,
                         url: Controller.config.get_menu,
                         columns: [
                             [
                                 {field: 'state', checkbox: true, },
                                 {field: 'menuName', title: __('Menu'), align:'left', formatter: function (value, row, index) {
                                 	return row.leaf == 0 ? '<span class="folder" data-t-id="'+row.id+'" data-t-name="'+row.menuName
                                 			+'" data-t-parent-id="'+row.parentId+'" data-t-parent-name="'+row.parentName+'">'+value+'</span>'
                                 			: '<span class="file" data-t-id="'+row.id+'" data-t-name="'+row.menuName
                                 			+'" data-t-parent-id="'+row.parentId+'" data-t-parent-name="'+row.parentName+'">'+value+'</span>';
                                 }},
                             ]
                         ],
                         onPostBody: function() {
         					$.each($('tr').find('td:eq(1)'), function(i, td) {
         						var s = $(td).find('span');
         						s.parents('tr').attr('data-tt-id', s.attr('data-t-id')).attr('data-tt-name', s.attr('data-t-name'));
         						s.parents('tr').attr('data-tt-parent-id', s.attr('data-t-parent-id')).attr('data-tt-parent-name', s.attr('data-t-parent-name'));
         					});
         					// 表格树
         					roleMenuTable.treetable('destroy').treetable({
         					    expandable: false,
            			        column: 1
         					});
                         },
                         onCheck: function(row) {
                         	roleMenuTable.bootstrapTable('checkBy', {field: 'id', values: [row.parentId]});
                          },
                          onUncheck: function(row) {
                         	 var uncheck = true;
                         	 var ids = [];
                         	 var rows = roleMenuTable.bootstrapTable('getAllSelections');
                         	 $.each(rows, function(i, r) {
                         		 if(r.parentId==row.parentId) {
                         			 uncheck = false;
                         		 }
                         		 if(r.parentId==row.id) {
                         			 ids.push(r.id);
                         		 }
                         	 });
                         	 uncheck && ids.push(row.parentId);
                         	 roleMenuTable.bootstrapTable('uncheckBy', {field: 'id', values: ids});
                          }
                     });
                     // 为表格绑定事件
                     Table.api.bindevent(roleMenuTable);
                     i++;
            	}
            });
            // 查询角色菜单
            roleTable1.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table fa.event.check', function () {
            	roleMenuTable.bootstrapTable('uncheckAll');
                var ids = Table.api.selectedids(roleTable1);
                if(ids.length) {
                	Util.api.ajax({
                		type: 'get',
                		url: '/role/read/menu',
            			data : {roleId : ids[0]},
                	}, function(result) {
                		roleMenuTable.bootstrapTable("checkBy", {field:"id", values: result.rows});
                	});
                }
            });
            // 保存角色菜单
            $('#roleMenu').on('click', '.btn-save', function() {
            	var roleIds = Table.api.selectedids(roleTable1);
            	var menuIds = Table.api.selectedids(roleMenuTable);
            	var data = [ {roleId: roleIds[0], permission: 'read'} ];
            	$.each(menuIds, function(i, menuId) {
        			data.push({roleId: roleIds[0], menuId: menuId, permission: 'read'});
        		});
            	if(roleIds.length && menuIds.length) {
                	Util.api.ajax({
                		type: 'POST',
                		url: '/role/update/menu',
            			data : JSON.stringify(data),
            			contentType: 'application/json;charset=UTF-8'
                	}, function(result) {
                		Toastr.success('保存成功.');
                	});
                }
            });
        },
        initRolePromission: function () {
        	var j = 0;
            var menuTree;
            var roleTable2 = $("#roleTable2");
            $('[href="#rolePromission"]').on('click', function() {
            	if(j === 0) {
                    // 初始化表格
                    roleTable2.bootstrapTable({
                    	toolbar: '#toolbar5',
                    	showExport: false,
                    	singleSelect: true,
                        url: Controller.config.get_role,
                        columns: [
                            [
                                {field: 'state', checkbox: true, },
                                {field: 'id', title: 'ID'},
                                {field: 'roleName', title: '角色名称'},
                                {field: 'deptName', title: __('Deptname')},
                            ]
                        ]
                    });
                    // 为表格绑定事件
                    Table.api.bindevent(roleTable2);            		
                    
                    $('.box-header .btn-refresh').on('click', function() {
                    	$('#menuTree').html('正在努力加载数据中，请稍候......');
                        Util.api.ajax({
                    	   type: 'get',
                    	   url: Controller.config.get_promission,
                    	   data: {keyword: ''}
                    	 }, function(result) {
              			   var data = result.rows;
            			   for(var i=0;i<data.length;i++) {
            				   data[i]['pId'] = data[i].parentId;
            				   data[i]['name'] = data[i].menuName;
            			   }
            			   menuTree = $.fn.zTree.init($('#menuTree'), {
            			        view: {
            			            dblClickExpand: false
            			        },
            			        data: {
            			            simpleData: {
            			                enable: true
            			            }
            			        },
            			        check: {
            			        	enable: true,
            			        	chkboxType : {
            			        		"Y" : "ps",
            			        		"N" : "ps"
            			        	}
            			        }
            			    }, data);
                    	});
                    });
                    $('.box-header .btn-refresh').click();
                    j++;
            	}
            });

            // 查询角色权限
            roleTable2.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table fa.event.check', function () {
            	menuTree.checkAllNodes(false);
                var ids = Table.api.selectedids(roleTable2);
                if(ids.length) {
                	Util.api.ajax({
                		type: 'get',
                		url: '/role/read/permission',
            			data : {roleId : ids[0], permission: ''}
                	}, function(result) {
                		var roleIds = [];
                		if (result.code == 200) {
                			var rows = result.rows;
                			 var nodes = menuTree.getCheckedNodes(false);
        					 for(var i=0; i< rows.length;i++) {
        						var p = rows[i];
        						$.each(nodes, function(index, treeNode) {
        							if(treeNode.parentId == p.menuId && treeNode.code == p.permission) {
        								menuTree.checkNode(treeNode, true, true);
        							}
        						});
        					}
        				}
                	});
                }
            });
            // 保存角色权限
            $('#rolePromission').on('click', '.btn-save', function() {
            	var roleIds = Table.api.selectedids(roleTable2);
            	var data = [ ];
        		var nodes = menuTree.getCheckedNodes(true);
    			if(nodes.length > 0) {
    	    		$.each(nodes, function(index, treeNode) {
    	    			if(treeNode.code) {
    		    			data.push({ roleId: roleIds[0], menuId: treeNode.parentId, permission: treeNode.code });
    	    			}
    	    		});
    			} else {
    				data.push({ roleId: roleIds[0] });
    			}
            	if(nodes.length && roleIds.length) {
                	Util.api.ajax({
                		type: 'POST',
                		url: '/role/update/permission',
            			data : JSON.stringify(data),
            			contentType: 'application/json;charset=UTF-8'
                	}, function(result) {
                		Toastr.success('保存成功.');
                	});
                }
            });
        }
    };
    return Controller;
});